using System;
using System.Drawing;
using System.IO;
using System.Web.UI.WebControls;

using Impact.Web.Foundation.Controls;
using Impact.Model.Service;
using Impact.Model.Objects;
using Impact.Controllers;

using StructureMap;

namespace Impact.Web.Admin
{
    public partial class UploadPhoto : Impact.Web.Foundation.PageBase
    {

        /// <summary>
        /// loading event handler
        /// </summary>
        protected override void OnLoad( EventArgs e )
        {
            if ( string.IsNullOrEmpty( Request.QueryString["gid"] ) )
            {
                throw new ArgumentException( "Must supply gallery ID" );
            }

            base.OnLoad( e );
        }

        /// <summary>
        /// event handler executed when the user clicks "Upload"
        /// </summary>
        protected void UploadCommand( object sender, CommandEventArgs e )
        {
            IPhotoService service = ObjectFactory.GetInstance<IPhotoService>();
            PhotoGallery gallery = service.GetGallery( Request.QueryString["gid"] );
            string galleryPath = Server.MapPath( PhotoController.GetGalleryPath( gallery ) );
            if ( !Directory.Exists( galleryPath ) )
            {
                Directory.CreateDirectory( galleryPath );
            }

            string ext = Path.GetExtension( uploadFile.PostedFile.FileName ).ToLower();
            if ( ext.Equals( ".jpg" ) || ext.Equals( ".jpeg" ) || ext.Equals( ".gif" ) || ext.Equals( ".png" ) )
            {
                string filename = Path.Combine( galleryPath, Path.GetFileName( uploadFile.PostedFile.FileName ) );
                uploadFile.PostedFile.SaveAs( filename );

                MessageBox.Show( string.Format( "Uploaded {0} kb successfully.", uploadFile.PostedFile.ContentLength / 1024 ) );
                Response.Redirect( Request.Url.ToString() );
            }
            else
            {
                message.Text = "Only image files are allowed to be uploaded into photo galleries.";
                message.ForeColor = System.Drawing.Color.Red;
            }

        }

    }
}
